// pages/login/login.ts
import api from "../../api/index";
import {ResDto} from "../../types";
import common from "../../common/index";
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    statusBarHeight: app.globalData.statusBarHeight,
    navBarHeight: app.globalData.navBarHeight,

    protocolChecked: false,
    manualLoginShow: false,
    codeLoading: false,
    phone: '',
    code: '',
    downCount: 60,
    downTimer: null,
    single: false, // 标识当前是否是关闭了应用其它所有页面，仅有登录页
  },
  handleProtocolCheckedChange() {
    this.data.protocolChecked = !this.data.protocolChecked
    this.setData({
      protocolChecked: this.data.protocolChecked,
    })
  },
  handlePopCheckedTip() {
    wx.showToast({
      title: '请先阅读并同意所有协议',
      icon: 'none'
    })
  },
  handleGotoH5(e:BaseEvent){
    const type = e.currentTarget.dataset.type
    wx.navigateTo({
      url: '/pages/h5/h5?type='+type,
    })
  },
  async getUserInfo(uid: string) {
    const userInfo: any = {}
    try {
      const res: any = await api.getUserInfo({uid})
      if (res && res.uid) {
        userInfo.nickname = res.nickname
        userInfo.icon = res.icon.replace(/.*?(?=\/user_portrait)/, '')
        userInfo.uid = res.uid
        userInfo.is_bind_wechat = res.is_bind_wechat || false
        userInfo.is_bind_external_wechat = res.is_bind_external_wechat || false
      }
    } catch(e) {
      console.log(e)
    }
    return userInfo
  },
  async getUserPortrait(uid: string) {
    let result = null
    try {
      const res = await api.getPortrait({uid})
      if (res.data) {
        result = res.data
      }
    } catch (e) {
      console.log(e)
    }
    return result
  },

  handleGetPhoneNumber(e: BaseEvent) {
    const self = this;
    if (e.detail.code) {
      wx.login({
        success(res) {
          wx.showLoading({
            title: '加载中'
          })
          api.wxLogin({
            phoneCode: e.detail.code,
            loginCode: res.code,
            state: ''
          }).then(async (res) => {
            if (res.data && res.data.userId) {
              res.data.userId = res.data.userId + ''
              common.setLocalUid(res.data.userId)
              const userInfo = await self.getUserInfo(res.data.userId)
              common.setAppUserInfo(userInfo)
              common.setLocalToken(res.data.accessToken)
              const data = await self.getUserPortrait(res.data.userId)
              wx.hideLoading()
              if (data) {
                wx.switchTab({
                  url: '/pages/index/index',
                })
              } else {
                wx.showToast({
                  title: '请补充资料'
                })
                wx.reLaunch({
                  url: '/pages/my-archive/my-archive?single=true',
                })
              }
            } else {
              wx.hideLoading()
              wx.showToast({
                title: res.msg || '登录失败',
                icon: 'error',
              })
            }
          }).catch(() => {
            wx.hideLoading()
            wx.showToast({
              title: '登录异常',
              icon: 'error',
            })
          })
        }
      })
    } else {
      this.setData({
        manualLoginShow: true
      })
    }
  },
  async handleSendPhoneCode() {
    if (this.data.downCount !== 60 || !this.data.phone) {
      return
    }
    clearInterval(this.data.downCount)
    wx.showLoading({
      title: '加载中'
    })
    try {
      const res: ResDto = await api.getCode({
        mobile: this.data.phone,
        scene: '1',
      })
      wx.hideLoading()
      if (res.code === 0) {
        wx.showToast({
          title: '验证码发送成功',
          icon: 'success',
        })
        this.data.downCount = 59
        this.setData({
          downCount: this.data.downCount,
        })
        setInterval(() => {
          this.data.downCount -= 1
          if (this.data.downCount <=0) {
            clearInterval(this.data.downCount)
            this.data.downCount = 60
          }
          this.setData({
            downCount: this.data.downCount
          })
        }, 1000)
      } else {
        this.data.downCount = 60
        wx.showToast({
          title: '验证码发送失败',
          icon: 'error',
        })
      }
    } catch(e) {
      wx.hideLoading()
    }
  },
  async handleLogin() {
    if (!this.data.phone || !this.data.code) {
      return
    }
    if (!this.data.protocolChecked) {
      this.handlePopCheckedTip()
      return
    }
    wx.showLoading({
      title: '加载中'
    })
    try {
      const res: ResDto = await api.login({
        mobile: this.data.phone,
        code: this.data.code,
      })
      if (res.data && res.data.userId) {
        res.data.userId = res.data.userId + ''
        common.setLocalUid(res.data.userId)
        const userInfo = await this.getUserInfo(res.data.userId)
        common.setAppUserInfo(userInfo)
        common.setLocalToken(res.data.accessToken)
        const data = await this.getUserPortrait(res.data.userId)
        wx.hideLoading()
        if (data) {
          wx.switchTab({
            url: '/pages/index/index',
          })
        } else {
          wx.showToast({
            title: '请补充资料'
          })
          wx.reLaunch({
            url: '/pages/my-archive/my-archive?single=true',
          })
        }
      } else {
        wx.hideLoading()
        wx.showToast({
          title: res.msg || '登录失败',
          icon: 'error',
        })
      }
    } catch(e){

    }
  },
  closeManualLogin(){
    this.setData({
      manualLoginShow: false
    })
  },
  openManualLogin(){
    this.setData({
      manualLoginShow: true
    })
  },
  handleBack() {
    // 检查是否有上一页可以返回
    const pages = getCurrentPages()
    if (pages.length > 1) {
      wx.navigateBack()
    } else {
      // 如果没有上一页，返回首页
      wx.switchTab({
        url: '/pages/index/index'
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(query) {
    this.setData({
      single: query.single === 'true'
    })
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})